﻿using System.Web.UI;
using ReadyApps.Data;
using ReadyApps.Models.Wiki;
using System.Web.Routing;
using System;

namespace ReadyApps.Controllers
{
    class WikiController
    {
        #region Variables

        private IWikiPageRequest pageRequest;
        private IWikiDataProvider dataProvider;
        private ControlCollection controls;
        private IWikiUrlManager urlManager;

        #endregion

        #region Constructor

        public WikiController(IWikiPageRequest wikiPageRequest, IWikiDataProvider wikiDataProvider,
            ControlCollection controlCollection, IWikiUrlManager wikiUrlManager)
        {
            if (wikiPageRequest == null)
            {
                throw new ArgumentNullException("wikiPageRequest");
            }
            if (wikiDataProvider == null)
            {
                throw new ArgumentNullException("wikiDataProvider");
            }
            if (controlCollection == null)
            {
                throw new ArgumentNullException("controlCollection");
            }
            if (wikiUrlManager == null)
            {
                throw new ArgumentNullException("wikiUrlManager");
            }
            pageRequest = wikiPageRequest;
            controls = controlCollection;
            dataProvider = wikiDataProvider;
            urlManager = wikiUrlManager;
        }

        #endregion

        #region Public Methods

        public void GenerateControls()
        {
            WikiPage page = new WikiPage(urlManager);

            WikiPageData pageData = dataProvider.GetWikiPageData(pageRequest.SiteName,
                pageRequest.GetFullPath(), pageRequest.RequestedPage);

            if (pageData != null)
            {
                page.GenerateWikiComponentsFromPageData(pageData);
            }
            else
            {
                page.GenerateWikiComponentsForNonExistentPage();
            }

            foreach (var component in page.GetWikiComponents())
            {
                controls.Add(component.GetControl());
            }
        }

        #endregion
    }
}
